package com.mingsoft.led.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import com.mingsoft.led.FileBean;

public class Configure {
	private Properties prop = new Properties();
	private static final String FILE_NAME = "/led.cfg";

	public static final String KEY_ADMIN_PWD = "KEY_ADMIN_PWD";
	public static final String KEY_ROOT_PATH = "KEY_ROOT_PATH";
	public static final String KEY_CAMERA_CFG = "KEY_CAMERA_CFG";
	public static final String KEY_FILE_MANAGEMENT_URL = "KEY_FILE_MANAGEMENT_URL";
	public static final String KEY_WELCOME_PATH = "KEY_WELCOME_PATH";

	private Configure() {
		File f = null;
		try {
			f = new File(Configure.class.getResource(FILE_NAME).getFile()
					.replace("%20", " "));
		} catch (Exception e1) {
			e1.printStackTrace();
			f = new File("led.cfg");
		}
		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(f.getAbsolutePath());
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			prop.load(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static Configure configure = new Configure();

	public static Configure getInstance() {
		return configure;
	}

	public String get(String key) {
		return prop.getProperty(key);
	}

	public boolean set(String key, String value) {
		String currentValue = prop.getProperty(key);
		if (value == null) {
			prop.remove(key);
		} else if (value != null) {
			prop.setProperty(key, value);
		}

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(Configure.class.getResource(FILE_NAME)
					.getFile().replace("%20", " "));
			prop.store(fos, "");
			FileBean.getInstance().setTimestmp(null);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			if (currentValue != null) {
				prop.setProperty(key, currentValue);
			} else {
				prop.remove(key);
			}
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
}
